import requests
import os
import time
import yaml
import json
import string

from PIL import Image, ImageDraw, ImageFont


def get_token(
        app_id='',  # 微信公众号AppID
        app_secret=''  # 微信公众号AppSecret
):
    """
    获取token
    :return:
    """
    url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}'
    res = requests.get(url=url)
    result = res.json()
    if result.get('access_token'):
        token = result['access_token']
        print(f"获取token成功：{token[:14]}****")
        return token
    else:
        print(f"获取token失败--{result}")


def refresh_token():
    """
    token刷新机制
    :return:
    """
    app_token_path = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'app_token.yaml'
    try:
        # 读取时间和token
        if not os.path.exists(app_token_path):
            with open(app_token_path, 'w+') as f:
                f.write('')
        cfg_token = yaml_read(app_token_path)
        t = cfg_token['time']
        record_token = cfg_token['token']
        cur_time = time.time()
        # token时间在7200s之内，返回token
        if 0 < cur_time - t < 7200:
            # print(f"token时效内")
            return record_token
        # token过期，刷新时间和token
        else:
            # print('token已过期')
            token = get_token()
            if token:
                data = {'time': time.time(), 'token': token}
                yaml_clear(app_token_path)
                yaml_write(data, app_token_path)
                return token
    except TypeError:
        # 获取初始时间和token
        print('获取初始token')
        token = get_token()
        data = {'time': time.time(), 'token': token}
        yaml_write(data, app_token_path)
        return token


def yaml_read(file):
    """
    yaml文件读取
    :param file:
    :return:
    """
    with open(file=file, mode="r", encoding="utf-8") as f:
        data = yaml.safe_load(f.read())
    return data


def yaml_write(data, file):
    """
    yaml文件写入
    :param data:
    :param file:
    :return:
    """
    with open(file, 'a', encoding='utf-8') as f:
        yaml.dump(
            data,
            stream=f,
            allow_unicode=True,  # 避免unicode编码问题
            sort_keys=False  # 不自动排序
        )


def yaml_clear(file):
    """
    yaml文件清空
    :param file:
    :return:
    """
    with open(file, 'w', encoding='utf-8') as f:
        f.truncate()


def get_material_list(count=20, offset=0, material_type='image'):
    """
    获取永久素材列表
    :param count: 返回素材的数量，取值在1到20之间
    :param offset: 0表示从第一个素材返回
    :param material_type: 素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news
    :return:
    """
    url = f"https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={refresh_token()}"
    page_data = []  # 用于存储所有数据
    while True:
        data = {"type": material_type, "offset": offset, "count": count}  # 构造分页参数
        res = requests.post(url=url, json=data)
        if res.status_code != 200 or res.json().get('errcode'):  # 请求失败时中断
            print(f'获取永久素材列表失败--{res.text}')
            break
        result = json.loads(res.content)  # 使用result=res.json()，响应结果中文乱码
        total_count = result.get('total_count')
        page_data.extend(result['item'])
        if total_count is not None and offset >= total_count:  # 没有更多页时中断
            break
        offset += count
    print(f'获取素材列表成功')
    print(page_data)
    return page_data


def get_hotimg(hotdataall):
    """
    下载热搜图片
    hotdata: 所有数据
    """

    if hotdataall:
        for hotdata in hotdataall:
            try:
                # 发送HTTP GET请求获取图片数据
                response = requests.get(hotdata['pic'], timeout=10)
                # 检查请求是否成功
                if response.status_code == 200:
                    # 获取Content-Type头信息
                    content_type = response.headers.get('Content-Type')

                    # 根据Content-Type判断图片类型
                    image_extension = None
                    if content_type == 'image/jpeg':
                        image_extension = '.jpg'
                    elif content_type == 'image/png':
                        image_extension = '.png'
                    elif content_type == 'image/gif':
                        image_extension = '.gif'
                    else:
                        raise Exception(f"Unsupported image type: {content_type}")

                    # 以二进制写模式打开文件，并将图片数据写入文件
                    img_name = "hotimg/orgimg/" + str(hotdata['index']) + image_extension
                    img_name_new = "hotimg/nowimg/" + str(hotdata['index']) + image_extension
                    with open(img_name, 'wb') as file:
                        file.write(response.content)
                    print(f'图片已保存到 {img_name}')

                    hotdata['image_path'] = img_name
                    hotdata['image_path_new'] = img_name_new
                else:
                    print(f'下载图片失败，状态码: {response.status_code}')
            except requests.RequestException as e:
                print(f'请求出现异常: {e}')


def add_text_to_image(image_path, image_path_new, text='', max_width=500):
    '''
    给图片添加文字
    '''
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)
    width, height = image.size

    font_size = max(30, int(width * 0.03))

    font = ImageFont.truetype("ttf/feihuasongti.ttf", font_size)
    text_color = (255, 255, 255)  # 黑色字体
    shadow_color = (0, 0, 0)  # 黑色阴影
    # text_width, text_height = draw.textsize(text, font=font)
    # 获取文本尺寸
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    while text_width > width - 30:
        font_size -= 1
        font = ImageFont.truetype("ttf/feihuasongti.ttf", font_size)
        # text_width, text_height = draw.textsize(text, font=font)
        # 获取文本尺寸
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]

    # 计算文本位置
    x = width - text_width
    y = height - text_height - 30
    # 绘制文本阴影
    draw.text(((x/2) + 2, y + 2), text, font=font, fill=shadow_color)
    draw.text((x / 2, y), text, font=font, fill=text_color)

    image.save(image_path_new)
    print(f'图片已加文字 {image_path_new}')


def add_media(hotdataall):
    """
    新增临时素材: https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
    上传图文消息内的图片获取URL, 新增永久素材: https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
    新增其他类型永久素材, 新增永久素材: https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE
    """
    # url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={refresh_token()}&type=image"
    # url = f"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={refresh_token()}"
    url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={refresh_token()}&type=image"

    image_id_list = []

    # 先上传封面
    # 封面地址：hotimg/cover.png
    with open("hotimg/1-cover.png", 'rb') as fp:
        files = {'media': fp}
        res = requests.post(url, files=files)
        res = json.loads(str(res.content, 'utf8'))
        image_id_list.append({"image_media_id": res['media_id']})
        print(f'封面图片已上传 hotimg/1-cover.png')

    if hotdataall:
        for hotdata in hotdataall:
            with open(hotdata['image_path_new'], 'rb') as fp:
                files = {'media': fp}
                res = requests.post(url, files=files)
                res = json.loads(str(res.content, 'utf8'))
                image_id_list.append({"image_media_id": res['media_id']})

                # hotdata["wx_img_url"] = res['url']
                print(f'图片已上传 {hotdata['image_path_new']}')


    # image_id_list.reverse()
    # print(image_id_list)
    return image_id_list


def get_drawing():
    '''
    获取草稿
    '''
    url = f"https://api.weixin.qq.com/cgi-bin/draft/batchget?access_token={refresh_token()}"
    data = {"offset": 0, "count": 20}  # 构造分页参数
    res = requests.post(url=url, json=data)

    result = json.loads(res.content)

    aaa = result['item'][0]

    bbb = json.dumps(aaa)
    print(aaa)

    # url = f"https://api.weixin.qq.com/cgi-bin/draft/get?access_token={refresh_token()}"
    # data = {"media_id": "V4QdIouS1e-m5FaD0_0keQ8o2_rK36fZtwdqB2cwd4IdRYCbJxBD4m6n66cIW54h"}

    # res = requests.post(url=url, json=data)

    # result = json.loads(res.content)
    # print(result)


def add_draft(hotdataall, image_id_list):
    '''
    新建草稿
    新建小绿书草稿
    小绿书 content。仅支持纯文本。换行符 \n
    '''
    url = f'https://api.weixin.qq.com/cgi-bin/draft/add?access_token={refresh_token()}'


    # 先定义一个字符串
    content_str = ""

    # 先组合content数据
    # 动态生成草稿content内容片段
    for hotdata in hotdataall:
        # 获取变量
        num = hotdata['index'] - 1
        title_title = hotdata['title']
        describe = hotdata['desc']

        # 判断是否循环到了 最后一个元素。最后一个元素 需要去掉 两个\n
        if hotdata['index'] == 11:
            # 最后一个
            tmp_str = f"Top {num}\n{title_title}\n{describe}"

            content_str += tmp_str
        else:
            # 不是最后一个
            # 组合文字
            tmp_str = f"Top {num}\n{title_title}\n{describe}\n\n"

            content_str += tmp_str

    # print("内容：", content_str)

    data = {
        "articles": [
            {
                "article_type":"newspic",
                "title":"今日热搜揭秘：全网热议哪些话题？",
                "content":content_str,
                "need_open_comment":1,
                "only_fans_can_comment":0,
                "image_info": {
                    "image_list": image_id_list
                }
            }
        ]
    }

    res = requests.post(url=url, data=json.dumps(data, ensure_ascii=False).encode('utf-8'))

    if res.status_code == 200:
        result = json.loads(res.content)
        if result.get('media_id'):
            print(f'新建草稿成功--{result}')
            return result['media_id']
        else:
            print(f'新建草稿失败--{result}')
    else:
        print(f'新建草稿失败--{res.text}')


def free_publish(media_id):
    '''
    发布草稿
    '''
    url = f'https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={refresh_token()}'

    data = {
        "media_id": media_id
    }

    res = requests.post(url=url, json=data)
    res = json.loads(str(res.content, 'utf8'))
    print(res)


def del_media(image_id_list):
    '''
    删除上传的素材 避免素材过多
    '''
    url = f'https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={refresh_token()}'


    for image_id in image_id_list:
        data = {
            "media_id": image_id['image_media_id']
        }


        res = requests.post(url=url, json=data)

    print("删除素材成功")


# 获取热搜数据
def get_hotdata():
    '''
    获取百度热搜的数据
    url网上找的: https://dabenshi.cn/other/api/hot.php?type=baidu
    '''
    url = f"https://dabenshi.cn/other/api/hot.php?type=baidu"
    hotdata = [] # 存储所有的热搜数据

    res = requests.get(url=url)
    result = res.json()
    hotdata = result['data'][1:11]

    # 下载图片
    get_hotimg(hotdata)

    # 给图片加上文字
    if hotdata:
        for hotdata_in in hotdata:
            image_path = hotdata_in['image_path']
            image_path_new = hotdata_in['image_path_new']
            text = hotdata_in['title']
            max_width = 500

            add_text_to_image(image_path, image_path_new, text=text, max_width=max_width)

    # 上传素材到公众号
    image_id_list = add_media(hotdata)

    # 新建草稿
    media_id = add_draft(hotdata, image_id_list)

    # # 发布草稿
    free_publish(media_id)

    # 删除上传的素材 避免素材过多
    del_media(image_id_list)


if __name__ == '__main__':
    get_hotdata()
    # get_drawing()
    # add_draft()
    # get_material_list()

